﻿using UnityEngine;

public class MeshBall : MonoBehaviour {

	static int baseColorId = Shader.PropertyToID("BaseColor"); //利用ID的方式获得Shader里面的元素

	[SerializeField]
	Mesh mesh = default;

	[SerializeField]
	Material material = default;

	Matrix4x4[] matrices = new Matrix4x4[1023];
	Vector4[] baseColors = new Vector4[1023];

	MaterialPropertyBlock block;

	void Awake() { //这里只使用了Awake，只有在Build了之后才会触发这个实例化
		for (int i = 0; i < matrices.Length; i++) {
			matrices[i] = Matrix4x4.TRS( //TRS是模型矩阵的三个参数 Trans Rotate Scale
				Random.insideUnitSphere * 10f, Quaternion.identity, Vector3.one
			);
			baseColors[i] =	
				new Vector4(Random.value, Random.value, Random.value, 1f);
		}
	}

	void Update() {
		if (block == null) {
			block = new MaterialPropertyBlock();
			block.SetVectorArray(baseColorId, baseColors); //装载参数
		}
		Graphics.DrawMeshInstanced(mesh, 0, material, matrices, 1023, block); //直接渲染Instance
	}
}